#include "TimeMgr.h"

#include <stdio.h>
#include <time.h>


std::string TimeMgr::toString() const
{
    time_t seconds = static_cast<time_t>(m_microSecondsSinceEpoch / kMicroSecondsPerSecond);
    int64_t microseconds = m_microSecondsSinceEpoch % kMicroSecondsPerSecond;
//    int microseconds = static_cast<int>(m_microSecondsSinceEpoch % kMicroSecondsPerSecond);

    struct tm tm_time;
//    gmtime_r(&seconds, &tm_time);//获取utc时间--------gmtime->线程不安全

#ifdef _WIN32
    struct tm* t = localtime(&seconds);//获取本地时间--------gmtime->线程不安全
    tm_time = *t;
#elif  __linux__
    localtime_r(&seconds, &tm_time);//获取本地时间--------gmtime->线程不安全
#endif


    char strTime[64];
    int len = snprintf(strTime, sizeof(strTime), "%4d-%02d-%02d %02d:%02d:%02d.%06ld",
                       tm_time.tm_year + 1900,
                       tm_time.tm_mon + 1,
                       tm_time.tm_mday,
                       tm_time.tm_hour,
                       tm_time.tm_min,
                       tm_time.tm_sec,
                       microseconds
                       );

//    std::cout << strTime << std::endl;
    return strTime;
}

int64_t TimeMgr::now()
{
    //微秒级精度
    struct timeval tv;
    gettimeofday(&tv, NULL);

    int64_t microSecondsSinceEpoch = static_cast<int64_t>(tv.tv_sec) * kMicroSecondsPerSecond + tv.tv_usec;

    return microSecondsSinceEpoch;
}
